//app.js
var constract = require('/utils/constract.js');

App({
  globalData: {
    ids:[],
    company: [],
    // globalAuth: true,
    getAuth: false,
    sourceList: ['请选择名片来源','展会','直客','代理'],
  },
  onLaunch: function () {
    wx.removeStorageSync("token_mm");
  },
  onShow: function(){
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    })

    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })

    })

    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      // console.log('新版本更新失败！');
    })

  },
  Verification:function(dl){ // 获取token
    var that = this;
    var token = wx.getStorageSync('token_mm');
    if (token) {
      typeof dl == "function" && dl(token);
      return;
    }
    wx.login({
      success: function (res) {
        wx.request({
          url: constract.login,
          data: { code: res.code },
          success: function (res2) {
            // console.log(res2);
            // console.log('2');
            var resAuth = res2.data.data.auth;
            if(resAuth === 0) {
              that.globalData.noAuth = true;
            } else {
              that.globalData.noAuth = false;
              token = res2.data.data.thirdSesson;
              typeof dl == "function" && dl(token);
              wx.setStorageSync('token_mm', token);
              return;
            }

            wx.getUserInfo({
              success: function (res3) {

                // console.log(res3);
                // console.log('3----成功获取授权');
                wx.request({
                  url: constract.register,
                  data: { thirdSesson: res2.data.data.thirdSesson, rawData: res3.rawData, signature: res3.signature, encryptedData: res3.encryptedData, iv: res3.iv },
                  success: function (res4) {
                    // console.log(res4);
                    // console.log('4');

                    that.globalData.getAuth = false;
                    token = res4.data.data;

                    // console.log(token);
                    // console.log(res2.data.data.thirdSesson);
                    // console.log('--------------------');

                    wx.setStorageSync('token_mm',token);
                    typeof dl == "function" && dl(token);
                  }
                })
              },
              fail: function (res5) { //拒绝授权,拿不到token
                // console.log('5');
                // console.log(res5);
                that.globalData.getAuth = true;

                typeof dl == "function" && dl(token);
                
              }
            })

          }
        })
      }
    })
  }
})